'use strict';

const Model = require("../model/index");
const Sequelize = require("sequelize");
const Controller = require("../core/base");
const moment = require("moment");

class StrategyListController extends Controller {
    // 发布行程经验
    async strategyAdd() {
        const { ctx } = this;
        const body = ctx.request.body;
        try {
            await Model.StrategyList.create({
                content: body.content,
                create_time: new Date(),
                update_time: new Date(),
                author: body.openid,
                pics: body.pics
            })
            this.success();
        } catch(err) {
            this.fail(err);
        }
    }
    // 获取行程经验列表
    async strategyList() {
        const { ctx } = this;
        const body = ctx.request.body;

        let where = {}
        if(body.type) {
            where.author = body.openid;
        }
        try {
            let rows = await Model.StrategyList.findAll({
                attributes: [Sequelize.col("user.username"), Sequelize.col("user.avatar"), "*"],
                include: [{
                    model: Model.UserList,
                    attributes: []
                }],
                where: where,
                raw: true
            }).then((rows) => {
                return rows.map(item => {
                    return {
                        ...item,
                        pics: item.pics && item.pics.split(",") || [],
                        year: moment(item.create_time).format("YYYY-MM-DD"),
                        day: moment(item.create_time).format("HH:mm:ss")
                    }
                })
            })
            this.success({
                data: rows
            })
        } catch(err) {
            this.fail(err);
        }
    }
}

module.exports = StrategyListController;